<template>
  <div class="container">
    <div class="fw p_bottom10 border_bottom">平台协议维护</div>
    <div class="main">
      <div>
        <div class="flex_js border_bottom" style="padding-bottom: 10px">
          <div>协议类型</div>
          <el-button
            type="primary"
            @click="show_box = true"
            v-if="type_list.length > list?.length && has_role_list[0].has_role"
            >新增</el-button
          >
        </div>
        <el-menu
          class="el-menu-vertical-demo"
          size="small"
          unique-opened
          :default-active="current_menu_id"
          @select="
            (e) => {
              select_menu(e)
            }
          "
        >
          <el-sub-menu v-for="item in list" :key="item.id" :index="item.id">
            <template #title>
              <span style="color: #333">{{ item.name }}</span>
            </template>
            <el-menu-item
              v-for="item2 in item.agreementList"
              :index="item2.id"
              :key="item2.id"
              class="text_over menu_item"
              >{{ item2.name
              }}<span v-if="item2.status == 2">(使用中)</span></el-menu-item
            >
          </el-sub-menu>
        </el-menu>
      </div>
      <el-divider direction="vertical" style="margin: 0 10px"></el-divider>
      <div>
        <div :key="current_menu_id" style="height: 96%; margin-bottom: 10px">
          <wangeditor
            :text="notice"
            style="height: 100%"
            :enable="
              current_menu_status == 1 ||
              (current_menu_status == 2 && !is_wait_publish)
            "
          ></wangeditor>
        </div>
        <div class="flex_js">
          <div></div>
          <div class="flex">
            <el-button
              type="primary"
              v-if="has_role_list[3].has_role && current_menu_status == 3"
              @click="delete_item"
              >删除</el-button
            >
            <el-button
              type="primary"
              v-if="
                has_role_list[1].has_role &&
                (current_menu_status == 1 ||
                  (current_menu_status == 2 && !is_wait_publish))
              "
              @click="save"
              >保存</el-button
            >
            <el-button
              type="warning"
              v-if="has_role_list[2].has_role && current_menu_status == 1"
              @click="pulish_item"
              >发布</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      :close-on-click-modal="false"
      @close="close_box"
    >
      <template #title>
        <h4>新增协议类型</h4>
      </template>
      <el-form label-width="100px">
        <el-form-item label="类型名称">
          <el-select v-model="add_form_data.code" placeholder="请选择">
            <el-option
              v-for="item in type_list"
              :key="item.id"
              :value="item.dictCode"
              :label="item.dictValue"
              :disabled="item.disable"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <div class="m_top10 tr">
        <el-button @click="close_box">取消</el-button>
        <el-button
          type="primary"
          @click="submit_add"
          :disabled="add_form_data.code == ''"
          >确定</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onUnmounted } from 'vue'
import { check_role, formatDate, dictData } from '@/utils/utils'
import wangeditor from '@/view/components/wangeditor.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
const has_role_list = ref([
  {
    path: 'agreement/post',
    has_role: false,
  },
  {
    path: 'agreement/put',
    has_role: false,
  },
  {
    path: 'agreement/publish',
    has_role: false,
  },
  {
    path: 'agreement/delete',
    has_role: false,
  },
])
const current_menu_id = ref()
const current_menu_status = ref<number>()
const current_type_id = ref()
const is_wait_publish = ref() // 判断当前菜单有无待发布
onMounted(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  get_list()
  EventBus.on('commit_editor', (e) => {
    if (wait_publish.value) {
      if ((e as any) != notice.value) {
        ElMessageBox.confirm('本次修改尚未保存，确定直接发布', '提示', {
          cancelButtonText: '直接发布',
          confirmButtonText: '保存后发布',
          closeOnClickModal: false,
          type: 'warning',
        })
          .then(() => {
            agree_submit(e)
          })
          .catch(() => {
            item_publish()
          })
      } else {
        ElMessageBox.confirm('确定发布该版本？将替换掉现使用中的版本', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          closeOnClickModal: false,
          type: 'warning',
        })
          .then(() => {
            item_publish()
          })
          .catch(() => {})
      }
    } else {
      agree_submit(e)
    }
  })
})
onUnmounted(() => {
  EventBus.off('commit_editor')
})
const list = ref([])
const notice = ref()
const add_form_data = ref({
  name: '',
  sort: '',
  code: '',
})
const type_list = ref([])
dictData('1628213630472294401').then((res) => {
  type_list.value = res as any
}) // 获取字典值 协议类型
const delete_item = () => {
  ElMessageBox.confirm('确定删除该历史版本？', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.agreement_crud + '/' + current_menu_id.value,
          method: 'delete',
        })
        .then((res) => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const wait_publish = ref(false)
const pulish_item = () => {
  wait_publish.value = true
  EventBus.emit('submit')
}
const item_publish = () => {
  axios
    .request({
      url: serviceApi.agreement_crud + '/publish/' + current_menu_id.value,
      method: 'put',
    })
    .then((res) => {
      ElMessage.success('操作成功！')
      setTimeout(() => {
        wait_publish.value = false
        get_list()
      }, 1000)
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const save = () => {
  ElMessageBox.confirm('确定保存本次修改', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      EventBus.emit('submit')
    })
    .catch(() => {})
}
const agree_submit = (e) => {
  axios
    .request({
      url: serviceApi.agreement_crud + '/' + current_menu_id.value,
      method: 'put',
      data: {
        agreementTypeId: current_type_id.value,
        content: e,
      },
    })
    .then((res) => {
      if (wait_publish.value) {
        item_publish()
      }

      ElMessage.success('操作成功！')
      setTimeout(() => {
        wait_publish.value = false
        console.log(res)
        get_list()
      }, 1000)
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const select_menu = (e) => {
  console.log(e)
  list.value.forEach((item) => {
    item.agreementList.forEach((item1) => {
      if (item1.id == e) {
        current_menu_id.value = item1.id
        notice.value = item1.content
        current_menu_status.value = item1.status
        current_type_id.value = item.id
        is_wait_publish.value = item.agreementList.at(-1).status == 1
      }
    })
  })
}
const show_box = ref()
const btn_loading = ref(false)
const submit_add = () => {
  if (add_form_data.value.code == '') {
    ElMessage.error('请选择协议类型')
    return
  }
  if (btn_loading.value) false
  btn_loading.value = true
  type_list.value.some((item) => {
    if (item.dictCode == add_form_data.value.code) {
      add_form_data.value.name = item.dictValue
    }
  })
  axios
    .request({
      url: serviceApi.agreement_type_crud,
      method: 'post',
      data: add_form_data.value,
    })
    .then(() => {
      ElMessage.success('操作成功！')
      setTimeout(() => {
        close_box()
        get_list()
      }, 1000)
    })
}
const get_list = () => {
  axios
    .request({
      url: serviceApi.agreement_type_list,
      method: 'post',
    })
    .then((res) => {
      if (res.data !== null && res.data.length) {
        res.data.forEach((item, index) => {
          type_list.value.forEach((item1) => {
            if (item1.dictCode == item.code) {
              item1.disable = true
            }
          })
          item.agreementList.forEach((item1) => {
            if (index == 0 && item1.status == 2) {
              is_wait_publish.value = item.agreementList.at(-1).status != 2
              current_menu_id.value = item1.id
              notice.value = item1.content
              current_menu_status.value = item1.status
              current_type_id.value = item.id
            }
            item1.name = formatDate(
              item1.updateTime === null
                ? parseInt(item1.startTime)
                : parseInt(item1.updateTime),
              'yyyy-MM-dd'
            )
              .split('-')
              .join('')
          })
        })
        list.value = res.data
      }
    })
}
const close_box = () => {
  add_form_data.value = {
    name: '',
    code: '',
    sort: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
:deep(.el-menu) {
  .el-sub-menu__title {
    background-color: #fff;
    &:hover {
      background-color: #fff;
    }
  }
  --el-menu-text-color: #333;
  --el-menu-hover-text-color: #333;
  --el-menu-bg-color: #fff;
  --el-menu-hover-bg-color: #fff;
}
.container {
  height: calc(100% - 40px);
  background-color: #fff;
  padding: 20px;
}
.main {
  margin-top: 10px;
  display: flex;
  align-items: center;
  height: calc(100% - 40px);
  > div {
    height: 100%;
  }
  > div:first-child {
    width: 300px;
  }
  > div:last-child {
    width: calc(100% - 320px);
  }
}
.menu_item {
  width: 200px;
  display: inline-block;
  box-sizing: border-box;
  padding-right: 0;
}
</style>
